<template>
  <div v-loading.fullscreen.lock="loading"
       :element-loading-text="$t('loading')"
       :class="['aui-wrapper', { 'aui-sidebar--fold': $store.state.sidebarFold , 'show-notice-banner': showNoticeBanner }]">
    <div>
      <template v-if="!loading">
        <notice-banner :showNoticeBanner.sync="showNoticeBanner"></notice-banner>
        <main-navbar @load="load" />
        <main-sidebar />
        <div class="aui-content__wrapper">
          <main-content v-if="!$store.state.contentIsNeedRefresh" />
        </div>
        <!-- hide theme tool 05/26-->
        <!-- <main-theme-tools /> -->
        <!--  -->
      </template>
    </div>
    <GetStarted ref="get-started-dialog"
                v-if="isShowGetStarted" />
    <DrillThrough />
    <AutoDetection />
    <DatasetTestDialog ref="DatasetTestDialog"></DatasetTestDialog>
  </div>
</template>

<script>
import MainNavbar from './main-navbar'
import MainSidebar from './main-sidebar'
import MainContent from './main-content'
import AutoDetection from './auto-detection'
import MainThemeTools from './main-theme-tools'
import GetStarted from './modules/mspbots/get-started/index'
import DrillThrough from './modules/mspbots/drill-through/dialog'
import roldIdList from '@/utils/config'
import { unionIntegrationList } from '@/components/storybook/utilties/tools'
import {setLoginPath, findSubjectCodeWithName } from '@/utils'
import { get } from 'lodash'
import {
  meta
} from '@/components/storybook/settings/router'
import { getMenuId } from '@/components/storybook/utilties/tools'
import DatasetTestDialog from '@/views/modules/mspbots/dataset/dataset-test-dialog.vue'
import { EventBus } from '@/utils/eventBus'
import { fetchSoftwareSetting } from '@/api/new'
import noticeBanner from "@/views/notice/notice-banner/notice-banner.vue";
export default {
  provide () {
    return {
      refresh () {
        this.$store.state.contentIsNeedRefresh = true
        this.$store.state.app.contentIsNeedRefreshCache = true
        this.$store.state.REFRESHCACHE = true

        this.$nextTick(() => {
          this.$store.state.contentIsNeedRefresh = false
        })
      }
    }
  },
  data () {
    return {
      loading: true,
      integrations: 0,
      isShowGetStarted: false,
      showNoticeBanner: false
    }
  },
  components: {
    MainNavbar,
    MainSidebar,
    MainContent,
    MainThemeTools,
    GetStarted,
    DrillThrough,
    AutoDetection,
    DatasetTestDialog,
    noticeBanner
  },
  watch: {
    $route: 'routeHandle',
    GetStartedDialogStatus (val) {
      if (val) {
        this.$refs['get-started-dialog'].openDialog()
        this.$store.state.GetStarted.dialogStatus = false
      }
    },
    thisTabName (val) {
      this.loadGetStartedDialog(val)
    }
  },

  created () {
    this.routeHandle(this.$route)
    this.getPSASetting()
    
    Promise.all([
      this.$store.dispatch('generateUser'),
      // this.$store.dispatch('getNextTicketAppList'),
      this.$store.dispatch('generateDicts'),
      this.$store.dispatch('generateButtons'),
      this.getLinkedInfo(),
      this.getThemeList()
      //this.getIntegrationsCount()
    ]).then(([{ roleList }]) => {
      this.$store.dispatch('getClientRoleList',this.$store.state.user.tenantCode)
      if (Array.isArray(roleList) && roleList.find(v => v.id === roldIdList.roleDashboardOnlyId)) {
        this.$router.replace({ path: '/portal' })
      }
      if (Array.isArray(roleList) && roleList.find(v => v.id === roldIdList.nextTicketRoleOnlyId)) {
        this.$router.replace({ path: '/nt' })
      }
      this.getIntegrationList()
      this.loading = false
      this.isShowGetStarted = true
    })
    EventBus.$on('sqlagent', ({data}) => {
      EventBus.$emit('closeDatasetTestDialog')
      if (data.message) {
        this.$message.error(data.message)
      } else if (Array.isArray(data)) {
        this.$refs.DatasetTestDialog && this.$refs.DatasetTestDialog.init(data)
      }
    })
  },

  computed: {

    GetStartedDialogStatus () {
      return this.$store.state.GetStarted.dialogStatus
    },
    thisTabName () {
      return this.$store.state.contentTabsActiveName
    }
  },
  methods: {

    load () {
      this.loading = false
      this.$nextTick(() => {
        this.loading = true
      })
    },
    loadGetStartedDialog (tabName) {
      // get dict list
      try {
        const startedConfig = window.SITE_CONFIG['dictList'].find(e => e.dictType === 'get-started-config').dataList
        const hasConfig = startedConfig.findIndex(e => e.dictLabel === tabName)
        if (hasConfig !== -1) {
          const thisConfig = startedConfig.find(e => e.dictLabel === tabName)
          let stepsList = thisConfig.dictValue.split(',')
          let undoneSteps = stepsList.find(e => this.$store.state.GetStarted.configList[e].status === 'undone')
          if (undoneSteps) {
            this.$store.state.GetStarted.steps = Number(undoneSteps)
            this.$refs['get-started-dialog'].openDialog()
          }
        }
      } catch (error) { }
    },
    tabRemoveHandle (tabName) {
      if (this.$store.state.user.regSource === '3' && tabName === 'mspbots-reports-index') {
        return false
      } else {
        if (tabName === 'home') {
          return false
        }
      }
      this.$store.state.contentTabs = this.$store.state.contentTabs.filter(item => item.name !== tabName)
      if (this.$store.state.contentTabs.length <= 0) {
        this.$store.state.sidebarMenuActiveName = this.$store.state.contentTabsActiveName = 'home'
        return false
      }
      if (tabName === this.$store.state.contentTabsActiveName) {
        let tab = this.$store.state.contentTabs[this.$store.state.contentTabs.length - 1]
        this.$router.push({
          name: tab.name,
          params: { ...tab.params },
          query: { ...tab.query }
        })
      }
    },
    routeHandle (route) {
      if (!get(route, 'meta.isTab', false)) {
        return
      }
      const routeMeta = get(route, 'meta') || {}
      const menuId = getMenuId(route)
      let tabIndex = -1
        if(this.$store.state.contentTabs){
            tabIndex = this.$store.state.contentTabs.findIndex(i => get(i, 'menuId') === menuId || (get(route, 'name') === 'home' && get(i, 'name') === get(route, 'name')))
        }
        const item = Object.assign({}, meta, {
        ...routeMeta,
        path: get(route, 'path'),
        params: route.params,
        query: route.query,
        name: get(route, 'query.name') || get(route, 'meta.title') || get(route, 'query.formTitle'),
        menuId,
        title: get(route, 'meta.title') || get(route, 'query.name') || get(route, 'query.formTitle')
      })
      if (tabIndex === -1) {
        this.$store.state.contentTabs.push(item)
      } else {
        this.$store.state.contentTabs.splice(tabIndex, 1, item)
      }
      this.$forceUpdate()
      this.$store.state.sidebarMenuActiveName = item.menuId
      this.$store.state.contentTabsActiveName = item.menuId
      this.$root.eventBus.$emit('pageActive')
    },

    getPermissions () {
      const params = {}
      if (sessionStorage.getItem('loginAsUserId')) {
        params.loginAsUserId = sessionStorage.getItem('loginAsUserId')
      }
      if (sessionStorage.getItem('loginAsRoleId')) {
        params.loginAsRoleId = sessionStorage.getItem('loginAsRoleId')
      }
      return this.$interface.system.getUserPermissionsApi(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        window.SITE_CONFIG['permissions'] = res.data
      }).catch(() => { })
    },
    getIntegrationList () {
      const params = {
        tenantCode: this.$store.state.user.tenantCode,
        loadType: 3
      }
      return this.$interface.taskManager.getConnectorInfoNew(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          for (var key1 in res.data) {
            if (!res.data[key1]) {
              delete res.data[key1]
            }
          }

          let mapObj = res.data
          let tempList = []
          let resultList = []
          for (let key in mapObj) {
            if (mapObj[key].sync.group === 2) {
              tempList.push({
                name: mapObj[key].name,
                subjectCode: mapObj[key].sync.subjectCode,
                status: mapObj[key].sync.status,
                group: mapObj[key].sync.group
              })
            }
          }

          for (let key in mapObj) {
            resultList.push({
              name: mapObj[key].name,
              subjectCode: mapObj[key].sync.subjectCode,
              status: mapObj[key].sync.status,
              group: mapObj[key].sync.group
            })
          }
          this.$store.state.user.integrationList = resultList
          this.integrations = this.integrations - ((this._.filter(resultList, { group: 2 })).length - (unionIntegrationList(tempList, 'subjectCode')).length)
          this.$store.commit('SET_INTEGRATIONS', this.integrations)
        })
        .catch(() => { })
    },
    getLinkedInfo () {
      var params = {
        page: 1,
        limit: 10,
        paramCode: 'in.line.knowledge.base'
      }
      this.$interface.system.getSystemParamsPage(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        const list = res.data.list
        if (list.length > 0) {
          this.$store.state.app.parameterKey = list[0].id
          window.SITE_CONFIG['wikiInfo'] = JSON.parse(list[0].paramValue)
        }
        this.loginGoTo()
      })
    },
    getThemeList () {
      var params = {
        page: 1,
        limit: 10,
        paramCode: 'themeList'
      }
      this.$interface.system.getSystemParamsPage(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        const list = res.data.list
        if (list.length > 0) {
          window.SITE_CONFIG['themeList'] = JSON.parse(list[0].paramValue)
        }
      })
    },
    getIntegrationsCount () {
      const params = {}
      if (sessionStorage.getItem('loginAsUserId')) {
        params.loginAsUserId = sessionStorage.getItem('loginAsUserId')
      }
      if (sessionStorage.getItem('loginAsRoleId')) {
        params.loginAsRoleId = sessionStorage.getItem('loginAsRoleId')
      }
      return this.$interface.taskManager.getIntegrationNumberApi(params).then(({ data: res }) => {
        this.integrations = res.data

        // this.getIntegrationList()
      })
    },
    getPSASetting () {
      fetchSoftwareSetting()
        .then(async ({ data: res }) => {
          try {
            if (res.data.software.selectedPSA[0]) {
              this.$store.state.user.psa = await findSubjectCodeWithName(res.data.software.selectedPSA[0])
            }
          } catch (error) {
          }
        })
        .catch(() => { })
    },
    loginGoTo () {
      let roleIdList = this.$store.state.user.roleList
      let findIndex1 = roleIdList.findIndex(e => e.id === '1524636890430033921')
      let findIndex = roleIdList.findIndex(e => e.id === '1266700345287905282')
      if (roleIdList.length === 2 && findIndex > -1 && findIndex1 > -1) {
        this.$router.replace({ name: 'desktop' })
      }
      if (roleIdList.length === 2 && roleIdList.findIndex(e => e.id === '1747869421395746817') > -1 && roleIdList.findIndex(e => e.id === '1747869610118455297') > -1) {
        this.$router.replace({ name: 'desktop' })
      }
      if (roleIdList.length === 1 && roleIdList.findIndex(e => e.id === '1747869421395746817') > -1 ){
        this.$router.replace({ name: 'desktop' })
      }
      if (roleIdList.length === 1 && roleIdList.findIndex(e => e.id === '1747869610118455297') > -1 ){
        this.$router.replace({ name: 'desktop' })
      }
    },
  },
  beforeDestroy () {
    EventBus.$off('sqlagent')
  }
}
</script>
<style lang="scss">
.el-submenu__title i {
  color: #404040 !important;
  font-weight: bold !important;
}
.show-notice-banner {
  padding-top: 100px !important;
  >div {
    >.aui-navbar {
      top: 50px;
    }
    >.aui-sidebar{
      top: 100px;
    }
    >.aui-content__wrapper {
      min-height: calc(100vh - 100px);
      >.aui-content {
        min-height: calc(100vh - 100px);
        >.aui-content--tabs-tools {
          top: 100px;
        }
        >.el-tabs {
          >.el-tabs__header {
            top: 100px;
          }
          >.el-tabs__content {
            height: calc(calc(100vh - 100px - 38px));
            >.el-tab-pane {
              min-height: calc(calc(100vh - 100px - 38px - 30px));
            }
          }
        }
      }
    }
  }
}
</style>
